package cn.com.flever.utils;

import cn.com.flever.component.AutoDeployDialog;
import cn.com.flever.entity.Sym3Config;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.intellij.execution.ui.ConsoleViewContentType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 　* @Description: TODO
 * 　* @author qiyu
 * 　* @date 2021/4/7 16:05
 *
 */
public class Sym3Utils {

    /**
     * 创建service
     * @param projectCode
     * @param cookie
     */
    public static void createService(String projectCode,String cookie)
    {
        try{
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部

            String projectConfig=Sym3Config.getConfig("serviceConfig.json").replaceAll("#PROJECT_CODE#",projectCode);
            JSONObject parm = JSONObject.parseObject(projectConfig);
            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>(parm, headers);
            ResponseEntity<String> response = restTemplate. postForEntity("https://***/api/v3/cube/namespaces/ntes-test/k8s-services", request, String.class);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 创建configmap
     * @param projectCode
     * @param cookie
     */
    public static void createCofnig(String projectCode,String cookie)
    {
        try{
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部

            String projectConfig=Sym3Config.getConfig("configMapConfig.json").replaceAll("#PROJECT_CODE#",projectCode);
            JSONObject parm = JSONObject.parseObject(projectConfig);
            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>(parm, headers);
            ResponseEntity<String> response = restTemplate.postForEntity("https://***/configmaps", request, String.class);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 创建application
     * @param projectCode
     * @param tag
     * @param cookie
     */
    public static void createApplication(String projectCode,String tag,String cookie)
    {
        try{
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部

            String projectConfig= Sym3Config.getConfig("applicationConfig.json").replaceAll("#PROJECT_CODE#",projectCode);
            projectConfig=projectConfig.replaceAll("#PROJECT_TAG#",tag);
            JSONObject parm = JSONObject.parseObject(projectConfig);
            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>(parm, headers);
            ResponseEntity<String> response = restTemplate.postForEntity("https://***/applications", request, String.class);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    /**
     * 更新application
     * @param projectCode
     * @param tag
     * @param cookie
     */
    public static void updateApplication(String projectCode,String tag,String cookie)
    {
        try{
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部
            headers.add(":authority","sym3.nie.netease.com");

            String projectConfig= Sym3Config.applicationConfig.replaceAll("#PROJECT_CODE#",projectCode);
            projectConfig=projectConfig.replaceAll("#PROJECT_TAG#",tag);
            JSONObject parm = JSONObject.parseObject(projectConfig);
            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>(parm, headers);
            restTemplate.put("https://***/ntes-test/applications/"+projectCode, request, String.class);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 查询服务是否部署完成
     * @param projectCode
     * @param cookie
     * @return
     */
    public static boolean queryApplicationStatus(String projectCode,String cookie)
    {
        try{
            boolean isOk=true;
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部

            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>( headers);
            ResponseEntity<String> exchange = restTemplate.exchange("https://***/ntes-test/pods", HttpMethod.GET, request, String.class);
            JSONArray pods =JSONObject.parseObject(exchange.getBody()).getJSONArray("pods");
            for(int i=0;i<pods.size();i++)
            {
                JSONObject item = pods.getJSONObject(i);
                String appName=item.getString("applicationName");
                String podName=item.getString("name");
                if(appName.equals(projectCode))
                {
                    /*获取pods的状态*/
                    JSONArray containerStatuses = item.getJSONArray("containerStatuses");
                    for(int j=0;j<containerStatuses.size();j++)
                    {
                        JSONObject pod = containerStatuses.getJSONObject(j);
                        JSONObject state = pod.getJSONObject("state");
                        if(state.containsKey("waiting")&&(state.getJSONObject("waiting").getString("reason").equals("ImagePullBackOff")||state.getJSONObject("waiting").getString("reason").equals("ErrImagePull")))
                        {
                            /*删除状态不正确的pod*/
                            deletepod(podName,cookie);
                            isOk=false;
                        }
                    }
                }
            }
            return isOk;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除指定pod
     * @param podName
     * @param cookie
     * @return
     */
    public static void deletepod(String podName,String cookie)
    {
        try{
            RestTemplate restTemplate=new RestTemplate(new OkHttp3ClientHttpRequestFactory());
            HttpHeaders headers = new HttpHeaders();
            List<String> cookies =new ArrayList<String>();
            /* 登录获取Cookie 这里是直接给Cookie，可使用下方的login方法拿到Cookie给入*/
            cookies.add(cookie);       //在 header 中存入cookies
            headers.put(HttpHeaders.COOKIE,cookies);        //将cookie存入头部

            HttpEntity<JSONObject> request = new HttpEntity<JSONObject>( headers);
            restTemplate.exchange("https://***namespaces/ntes-test/pods/"+podName, HttpMethod.DELETE, request, String.class);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    public static String getTokenFormCookie(String cookie)
    {
        String[] cookies = cookie.split(";");
        for (String item : cookies) {
            if(item.contains("ACCESS_TOKEN"))
            {
                return item.replace("ACCESS_TOKEN=","").trim();
            }
        }
        return "";
    }
}
